import os
import shutil
import socket
import threading
import time
from http.server import HTTPServer, SimpleHTTPRequestHandler

from PyQt5.QtCore import QObject, pyqtSignal


class SharingServer(QObject):
    sharing_started = pyqtSignal(str)  # 信号，传递分享URL
    sharing_stopped = pyqtSignal()

    def __init__(self, parent=None):
        super().__init__(parent)
        self.server = None
        self.port = 8000
        self.shared_dir = "shared"
        self.share_thread = None

    def get_local_ip(self):
        """获取本地IP地址"""
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(("8.8.8.8", 80))
            ip = s.getsockname()[0]
            s.close()
            return ip
        except:
            return "127.0.0.1"

    def start_sharing(self, file_path):
        """启动共享服务"""
        # 创建共享目录
        if not os.path.exists(self.shared_dir):
            os.makedirs(self.shared_dir)

        # 清空旧文件
        for f in os.listdir(self.shared_dir):
            os.remove(os.path.join(self.shared_dir, f))

        # 复制文件到共享目录
        if os.path.isfile(file_path):
            shutil.copy(file_path, self.shared_dir)
        elif os.path.isdir(file_path):
            for f in os.listdir(file_path):
                shutil.copy(os.path.join(file_path, f), self.shared_dir)

        # 查找可用端口
        while True:
            try:
                self.server = HTTPServer(
                    ('0.0.0.0', self.port),
                    lambda *args: SimpleHTTPRequestHandler(*args, directory=self.shared_dir)
                )
                break
            except OSError:
                self.port += 1

        # 在后台线程中运行服务器
        self.share_thread = threading.Thread(target=self.run_server, daemon=True)
        self.share_thread.start()

        # 生成分享URL
        ip = self.get_local_ip()
        url = f"http://{ip}:{self.port}/questions_export.zip"
        self.sharing_started.emit(url)

    def run_server(self):
        """运行HTTP服务器"""
        try:
            self.server.serve_forever()
        except:
            pass
        finally:
            self.server.server_close()

    def stop_sharing(self):
        """停止共享服务"""
        if self.server:
            self.server.shutdown()
            self.sharing_stopped.emit()
            time.sleep(1)  # 等待服务器完全关闭
